package marks

import (
	"errors"
	"os"
)

var LastObj *Object

var BucketName = []byte("test")

type HashChain struct {
	LastObj *Object
	Db *DB
}

func NewHashChain(path string) *HashChain {
	db := NewDB(path)
	LastHash := db.GetLastHash()
	return &HashChain{
		Db:db,
		LastObj:LastHash,
	}
}

func (this *HashChain)Add(bucketName []byte, hash []byte, obj *Object) error {
	bytes, e := Serialize(obj)
	if e != nil{
		return e
	}

	err := this.Db.Add([]byte(bucketName), []byte(hash), bytes)
	if err != nil {
		return err
	}else{
		this.LastObj = obj
	}

	return nil
}

func (this *HashChain)GetInfo() []*Object {
	_, e := os.Stat(DB_Path)
	if e != nil{
		return nil
	}
	obj := []*Object{}
	last := this.Db.GetLastHash()
	if last == nil{
		return obj
	}else {
		obj = append(obj,last )
		for last.PreHash != ""{
			bytes,err := this.Db.View([]byte("test"),[]byte(last.PreHash))
			if err != nil{
				return obj
			}

			object := &Object{}
			b := UnSerialize(bytes, object)
			if b == true{
				obj = append(obj,object )
				last = object
			}
			if len(obj) == 10{
				return obj
			}
		}
		return obj
	}

}

func (this *HashChain)View(hash string)(*Object, error)  {
	bytes, e := this.Db.View([]byte("test"), []byte(hash))
	if e != nil {
		return nil,e
	}else{
		var obj = &Object{}
		UnSerialize(bytes,obj)
		if obj == nil {
			return obj,errors.New("序列化失败")
		}
		return obj,nil
	}
}